package com.gvsoft.communication.server.socket;

import java.io.IOException;
import java.util.Map;

import com.gvsoft.communication.net.NSocket;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Created with IntelliJ IDEA.
 * ProjectName:gvMsgRouting
 * Author: zhaoqiubo
 * Date: 15/8/5
 * Time: 下午4:24
 * Desc: 超时通道、失效通道清理线程。
 */

public class NSocketCleanThread extends Thread {
    /**
     * 超时时间
     */
    private int outTime;
    /**
     * 执行周期
     */
    private int cycle;

    private static Logger logger = LogManager.getLogger("server");

    public NSocketCleanThread(int outTime, int cycle) {
        this.outTime = outTime;
        this.cycle = cycle;
        setName("NSocketCleanThread");
    }

    private static boolean interrupt = false;

    @Override
    public void interrupt() {
        interrupt = true;
        logger.info("中断socket清理线程！");
        super.interrupt();
    }

    public void run() {


        while (!interrupt) {

            Map<String, NSocket> connCache = NSocketManager.getConnCache();

            for (String token : connCache.keySet()) {
                int currentTime = (int) System.currentTimeMillis();
                NSocket nSocket = NSocketManager.getConnByToken(token);
                if (null != nSocket && !nSocket.getChannel().isOpen()) {
                    NSocketManager.removeNSocket(nSocket.getToken(), nSocket.getUserId());
                    nSocket.close();
                    logger.info("清理了关闭的连接：token:<" + token + ">，UserMapSize：" + NSocketManager.getUserMapSize()
                            + "，tokenMapSize：" + NSocketManager.getTokenMapSize());
                } else if (null != nSocket && (currentTime - nSocket.getLastAccessTime() > outTime * 1000)) {
                    if (nSocket.getChannel().isOpen()) {
                        NSocketManager.removeNSocket(nSocket.getToken(), nSocket.getUserId());
                        nSocket.close();
                        logger.info("清理了超时的连接：token:<" + token + ">，UserMapSize：" + NSocketManager.getUserMapSize()
                                + "，tokenMapSize：" + NSocketManager.getTokenMapSize());
                    }
                }
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    logger.error("NSocketCleanThread interrupt error:" + e.getMessage());
                    e.printStackTrace();
                }

            }
            try {
                Thread.sleep(cycle * 1000);
            } catch (InterruptedException e) {
                interrupt = true;
            }
        }
    }
}
